package hypeerweb;

import java.util.TreeSet;

public abstract class BroadcastVisitor implements Visitor {
	protected static String STARTED_KEY = "started";

	public void visit(Node node, Parameters parameters) {
		Object started = parameters.get(STARTED_KEY);
		if ((Boolean) started) {
			int modVal = 2;
			TreeSet<Node> neighbors = new TreeSet<Node>(node.getLargerNeighbors());
			operation(node, parameters);
			if (!neighbors.isEmpty())
				for (int i = 0; i < node.getWebId().getHeight(); i++) {
					if (node.getWebId().getValue() % modVal == 0) {
						if (!neighbors.isEmpty()) {
							Node first = neighbors.first();
							neighbors.remove(first);
							first.accept(this, parameters);
						}
					}
					modVal *= 2;
				}
		} else if (node.getWebId().getValue() == 0) {
			parameters.set(STARTED_KEY, true);
			visit(node, parameters);
		} else {
			goToNode0(node).accept(this, parameters);
		}

	}

	public static Parameters createInitialParameters() {

		return new Parameters();
	}

	private Node goToNode0(Node node) {
		return node.getSmallestNeighbor();
	}

	protected abstract void operation(Node node, Parameters parameters);
}
